<?php
App::import('Controller', 'Tickets');

class BacklogsController extends AppController 
{
	public $useTable = false;
	public $uses = array('Ticket');
	private $Tickets = null; //controller
	
	public function po_index()
	{
		//Class Tickets
		$this->Tickets = new TicketsController;
		$this->Tickets->constructClasses();
		
		//VARS
		$title_for_layout = __('Backlog do produto');
		$listTickets = $this->Tickets->_tickets();
		$listTicketsStatus = $this->Ticket->_ticketsStatus;
		
		//SET
		$this->set(compact('title_for_layout', 'listTickets', 'listTicketsStatus'));
	}

	public function po_priorize()
	{
		//UPDATE
		if ($this->params['form'])
		{
			$id = $this->params['form']['id'];
			$oldPosition = $this->params['form']['oldPosition'];
			$newPosition = $this->params['form']['newPosition'];
			
			//save priotiry of item moved
			$this->Ticket->id = $id;
			$this->Ticket->saveField('ticket_priority', $newPosition);
			
			//other items
			#defined the new priority
			$operator = ($oldPosition > $newPosition) ? array('+', '>=', '<=') : array('-', '<=', '>=');
			#update priority for other tickets
			$this->Ticket->updateAll(
				array('ticket_priority' => 'ticket_priority '.$operator[0].' 1'), //value
				array( //filters
					'Ticket.project_id' => $this->Session->read('Project.id'),
					'Ticket.id <>' => $id,
					'Ticket.ticket_priority '.$operator[1] => $newPosition,
					'Ticket.ticket_priority '.$operator[2] => $oldPosition
				)
			);
		}
		
		//Class Tickets
		$this->Tickets = new TicketsController;
		$this->Tickets->constructClasses();
		
		//VARS
		$title_for_layout = __('Priorizar itens do backlog');
		$listTickets = $this->Tickets->_tickets();
		
		//SET
		$this->set(compact('title_for_layout', 'listTickets'));
	}
}